package main

import (
	"fmt"

	"go-copyright-p2/configs"
	"go-copyright-p2/eths"
	"go-copyright-p2/routes"
	"go-copyright-p2/dbs"

	"github.com/gorilla/sessions"
	"github.com/labstack/echo"
	"github.com/labstack/echo-contrib/session"
	"github.com/labstack/echo/middleware"
	"github.com/robfig/cron"
)

var EchoObj *echo.Echo //echo框架对象全局定义
//静态html文件处理
func staticFile() {

	EchoObj.Static("/", "static/pc/home") //根目录设置
	EchoObj.Static("/static", "static")   //全路径处理
	EchoObj.Static("/upload", "static/pc/upload")
	EchoObj.Static("/css", "static/pc/css")
	EchoObj.Static("/assets", "static/pc/assets")
	EchoObj.Static("/user", "static/pc/user")
}

func main() {

	fmt.Printf("get config %v ,%v\n", configs.Config.Common.Port, configs.Config.Db.Connstr)
	EchoObj = echo.New()             //创建echo对象
	EchoObj.Use(middleware.Logger()) //安装日志中间件
	EchoObj.Use(middleware.Recover())
	EchoObj.Use(session.Middleware(sessions.NewCookieStore([]byte("secret"))))
	EchoObj.Use(middleware.GzipWithConfig(middleware.GzipConfig{
		Level: 5,
	}))

	go eths.EventSubscribe("ws://localhost:8546", configs.Config.Eth.PxaAddr)

	staticFile() //静态文件处理调用

	EchoObj.GET("/ping", routes.PingHandler)          //路由测试函数
	EchoObj.POST("/account", routes.Register)         //注册账户
	EchoObj.GET("/session", routes.GetSession)        //session获取
	EchoObj.POST("/login", routes.Login)              //登陆
	EchoObj.POST("/content", routes.Upload)           //上传图片
	EchoObj.GET("/content", routes.GetContents)       //查看当前用户图片
	EchoObj.GET("/content/:title", routes.GetContent) //查看单个图片
	EchoObj.POST("/auction", routes.Auction)          //发起拍卖
	EchoObj.GET("/auctions", routes.GetAuctions)      //查看拍卖
	EchoObj.GET("/auction/bid", routes.BidAuction)    //结束拍卖
	EchoObj.GET("/vote",routes.Vote)				  //投票

	EchoObj.Logger.Fatal(EchoObj.Start(configs.Config.Common.Port)) //启动服务

	//每天扫描排行榜对排行榜前3名进行奖励
	go rankAward()

}

func rankAward(){
	c := cron.New()
	c.AddFunc("@daily", func(){
		//获取排行前三的作品拥有者
		sql := "select v.content_hash, max(v.address) as address, count(*) as total from vote v left join account_content a on v.content_hash = a.content_hash group by v.content_hash order by total desc limit 3"
		ranks, num, err := dbs.DBQuery(sql)
		if num <= 0 || err != nil {
			fmt.Println("failed to query ranks", err)
		}
		//进行转账奖励
		for i := 0; i < len(ranks); i++{
			//Foundation默认密码为空，暂时这样写
			go eths.AwardPXC(ranks[i]["address"],"")
		}
	})
}
